//
//  MyfightersVC.m
//  u76ho
//
//  Created by m-air-01 on 15/12/28.
//  Copyright © 2015年 LV. All rights reserved.
//

#import "MyfightersVC.h"
#import "MyFightersTableViewCell.h"
#import "MyFighterDetailVC.h"
#import "ContactPeopleModel.h"
@interface MyfightersVC ()
<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    UITableView * _tableView;
    NSMutableArray * headerData;
    NSMutableArray * dataSource;
    
    NSMutableArray * selectedArr;
}
@property (strong, nonatomic) FeRollingLoader *rollingLoader;
@end
@implementation MyfightersVC
#pragma mark - 视图的生命周期
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];

}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
//    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
//    
//    self.navigationItem.backBarButtonItem = backBarButton;
    
    

    
    [self main];
    
    _rollingLoader = [[FeRollingLoader alloc] initWithView:self.view title:@"LOADING"];
    [self.view addSubview:_rollingLoader];
    
    [_rollingLoader show];
    

    
    if (_isSelectedPeople == YES) {
        self.navigationItem.title = @"选择战友";
    }
    else
    {
        self.navigationItem.title = @"联系人";
    }
    
   // self.navigationItem.title = @"我的战友";
    
    
    if (_isSelectedPeople == YES) {
        [self addItem];
    }
}
-(void)main
{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    headerData = [[NSMutableArray alloc]init];
    dataSource = [[NSMutableArray alloc]init];
    selectedArr = [[NSMutableArray alloc]init];
//    [headerData addObjectsFromArray:@[@"产品部",@"技术部"]];
//    NSMutableArray * arr1 =[[NSMutableArray alloc]init];
//    [arr1 addObjectsFromArray:@[@"张三",@"李思",@"王武"]];
//    NSMutableArray * arr2 =[[NSMutableArray alloc]init];
//    [arr2 addObjectsFromArray:@[@"佝偻"]];
//    [dataSource addObjectsFromArray:@[arr1,arr2]];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerNib:[UINib nibWithNibName:@"MyFightersTableViewCell" bundle:nil] forCellReuseIdentifier:@"MyFightersTableViewCell"];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self requestData];
}
-(void)requestData
{
    
    [U76HONet contactPeopleWithaction:@"" Code:[Singleton share].code Qycode:[Singleton share].yqcode andDataBlock:^(NSArray *arr) {
        NSLog(@"联系人获取成功");
        if (arr.count == 0) {
            [self nosearch];
            
            [_rollingLoader removeFromSuperview];
        }
        else
        {
            for (int i = 0; i<arr.count; i++) {
                ContactPeopleModel * model = arr[i];
                if (i == 0) {
                    if (model.bumen!=nil) {
                        [headerData addObject:model.bumen];
                    }
                    else
                    {
                        model.bumen = @"无部门";
                        [headerData addObject:model.bumen];
                    }
                }
                else
                {
                    if ([headerData containsObject:model.bumen]) {
                        
                    }
                    else
                    {
                        if (model.bumen!=nil) {
                            [headerData addObject:model.bumen];
                        }
                        else
                        {
                            model.bumen = @"无部门";
                            [headerData addObject:model.bumen];                        }
                    }
                }
            }
            
            for (int i = 0; i<headerData.count; i++) {
                NSMutableArray * tempArr = [[NSMutableArray alloc]init];
                NSMutableArray * tempArray = [[NSMutableArray alloc]init];
                for (int j = 0; j<arr.count; j++) {
                    ContactPeopleModel * model = arr[j];
                    if ([model.bumen isEqualToString:headerData[i]]) {
                        [tempArr addObject:model];
                        [tempArray addObject:@"0"];
                    }
                }
                [selectedArr addObject:tempArray];
                [dataSource addObject:tempArr];

            }
            
            [_rollingLoader removeFromSuperview];

            [_tableView reloadData];
        }
    }];
}
#pragma mark - _tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return headerData.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataSource[section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyFightersTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyFightersTableViewCell" forIndexPath:indexPath];
    cell.contactPeopleM = [[dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if (_isSelectedPeople == YES) {
        cell.isHiddenRightImg = YES;
    }
    if ([[[selectedArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqualToString:@"1"]) {
        UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        imgV.image = [UIImage imageNamed:@"选中图标"];
        cell.accessoryView = imgV;

    }
    else
    {
        cell.accessoryView = nil;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isSelectedPeople == YES) {
        
        NSString * s = selectedArr[indexPath.section][indexPath.row];
        NSMutableArray * arr = [[NSMutableArray alloc]init];
        [arr addObjectsFromArray:selectedArr[indexPath.section]];
        for (int i = 0; i<[arr count]; i++) {
            if ((int)indexPath.row == i) {
                if ([s isEqualToString:@"0"]) {
                    [arr replaceObjectAtIndex:i withObject:@"1"];
                }
                else
                {
                    [arr replaceObjectAtIndex:i withObject:@"0"];
                }
            }
        }
        
        [selectedArr replaceObjectAtIndex:indexPath.section withObject:arr];
        [_tableView reloadData];
    }
    else
    {
        if ([self isLogin]) {
            MyFighterDetailVC * detailVC = [[MyFighterDetailVC alloc]init];
            ContactPeopleModel * model = [[dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
            detailVC.friendCode = model.friendcode;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}
-(BOOL)isLogin
{
    if ([Singleton share].code) {
        NSLog(@"登录了");
        return YES;
        
    }
    else
    {
        //        NSLog(@"还没登录呢");
        //        LoginViewController * loginVC = [[LoginViewController alloc]init];
        //        [self.navigationController pushViewController:loginVC animated:NO];
        //        return NO;
        if (SYSTEM_VERSION >= 8.0) {
            UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录是否登录" preferredStyle:UIAlertControllerStyleAlert];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
//                app.window.rootViewController = nvc;
                LoginViewController * loginVC = [[LoginViewController alloc]init];
                UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
                nvc.navigationBarHidden = YES;
                
                [self presentViewController:nvc animated:YES completion:nil];
                
            }]];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }]];
            [self.view.window.rootViewController presentViewController:alerVC animated:YES completion:nil];
            
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录是否登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        return NO;
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = (int)buttonIndex;
    if (i == 0) {
        
    }
    else if(i == 1)
    {
        LoginViewController * loginVC = [[LoginViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
        nvc.navigationBarHidden = YES;
        
        [self presentViewController:nvc animated:YES completion:nil];
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [self addHeaderViewWithSection:section];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
-(void)nosearch
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    view.backgroundColor = UIColorFromRGB(0xf1f3f2);
    view.tag = 504;
    
    UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-98/2,SIZETO6H(120), 98, 100)];
    imgV.image = [UIImage imageNamed:@"苦脸"];
    [view addSubview:imgV];
    
    UILabel * tipLab = [[UILabel alloc]initWithFrame:CGRectMake(0, imgV.bottom+SIZETO6H(20), SCREEN_WIDTH, 20)];
    tipLab.text = @"暂时没有符合条件的内容";
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.font = [UIFont systemFontOfSize:14];
    tipLab.textColor = UIColorFromRGB(0x333944);
    [view addSubview:tipLab];
    [self.view addSubview:view];
}

#pragma mark - 设置头视图的View
-(UIView *)addHeaderViewWithSection:(NSInteger)section
{
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    headerView.backgroundColor = [UIColor whiteColor];
    UILabel * headerTextLab = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-15, 50)];
    headerTextLab.text = [headerData objectAtIndex:section];
    headerTextLab.textColor = UIColorFromRGB(0x333944);
    [headerView addSubview:headerTextLab];
    headerTextLab.font = [UIFont systemFontOfSize:20];
    return headerView;
}
#pragma mark - addItems
-(void)addItem
{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 40, 40);
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(finishBntAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
}
-(void)finishBntAction:(UIButton *)btn
{
    NSMutableArray * mArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<selectedArr.count; i++) {
        NSArray * arr = selectedArr[i];
        for (int j = 0; j<arr.count; j++) {
            NSString * str = arr[j];
            if ([str isEqualToString:@"1"]) {
                [mArr addObject:dataSource[i][j]];
            }
        }
    }
    if (mArr.count!=0) {
        NSMutableArray * tempmArr = [[NSMutableArray alloc]init];
        for (int i = 0; i<mArr.count; i++) {
            ContactPeopleModel * model = mArr[i];
            [tempmArr addObject:model.friendcode];
        }
        NSString * str = [tempmArr componentsJoinedByString:@","];
        [self.delegate selectedPeopleDelegatewithCodes:str];
    }
    else
    {
        [self.delegate selectedPeopleDelegatewithCodes:@""];
    }
    [self.navigationController popViewControllerAnimated:YES];
}



@end
